package com.taotao.portal.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.po.TbUser;
import com.taotao.portal.service.UserService;

public class LoginIntercepter implements HandlerInterceptor {

	@Autowired
	private UserService userService;
	
	@Value("${SSO_LOGIN_URL}")
	private String SSO_LOGIN_URL;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 调用Servcie 获取用户信息
		TbUser user = userService.getUserByToken(request, response);
		if (user==null) {
			// 重定向 到登录的页面  并且get方法提交用户登录成功后需要跳转的页面
			response.sendRedirect(SSO_LOGIN_URL+"?redirectUrl="+request.getRequestURL());
			return false;
		}
		// 把用户对象放在request里面
		request.setAttribute("user", user);
		// 放行
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
